<template>
  <van-form
    :ref="(ref: FormInstance) => initialization(ref)"
    :label-width="props.labelWidth"
  >
    <van-cell-group inset>
      <template v-for="field in props.fields" :key="field.key">
        <van-field :name="field.key" :label="field.label" :rules="field.rules">
          <template #input>
            <component
              :name="field.key"
              :is="field.el"
              v-model="formData[field.key]"
              v-bind="{
                ...field?.attrs,
                disabled: props.hiddenInActions || field?.attrs?.disabled
              }"
              :placeholder="
                field?.placeholder || field?.attrs?.placeholder || field.label
              "
            />
          </template>
        </van-field>
      </template>
    </van-cell-group>
    <div style="margin: 16px" v-if="!props.hiddenInActions">
      <slot name="buttons">
        <van-button round block type="primary" @click="formValidate">
          {{ props.submitText }}
        </van-button>
      </slot>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import formProps, { formEmits } from './form'

import { FormInstance } from 'vant'

import { useFormMethods } from './hooks'

const props = defineProps(formProps as any)

const { initialization, validate, resetValidation, formData } =
  useFormMethods(props)

const emits = defineEmits(formEmits)

const formValidate = () => {
  validate().then((formData: any) => {
    emits('getFormValidate', formData)
  })
}

defineExpose({
  resetValidation,
  validate
})

defineOptions({
  name: 'VForm'
})
</script>

<style scoped lang="scss">
.van-cell {
  align-items: center;
}
</style>
